// 向下取整 保留2位     <span>{{scope.row.collect }}{{getNum(scope.row.collect, true) }}</span>   100   kg parseFloat
// { Number } i  需要处理的数据
// {Number} x  true-返回单位   false-返回数字(默认) 
export function getNum(i, x = false) {
    if (i < 0) {
        i = i * -1;
        let n = 0
        let u = 'g'
        if (i < 1000) {
            if (x) return u
            else return i
        } else if (i < 1000 * 1000) {
            n = i / 1000
            u = 'kg'
        } else {
            n = i / 1000 / 1000
            u = 't'
        }
        let s = '-' + Math.floor(n * 100) / 100
        if (x) return u
        else return s
    } else {
        let n = 0
        let u = 'g'
        if (i < 1000) {
            if (x) return u
            else return i
        } else if (i < 1000 * 1000) {
            n = i / 1000
            u = 'kg'
        } else {
            n = i / 1000 / 1000
            u = 't'
        }
        let s = Math.floor(n * 100) / 100
        if (x) return u
        else return s
    }
}
// 金额转大写   贰拾圆
export function toChinesNum(number) {
    let ret = "";
    if (number !== "" && number != null && number !== "0") {
        let unit = "仟佰拾亿仟佰拾万仟佰拾元角分";
        let str = "";
        number += "00";
        const point = number.indexOf(".");
        if (point >= 0) {
            number = number.substring(0, point) + number.substr(point + 1, 2);
        }
        unit = unit.substr(unit.length - number.length);
        for (let i = 0; i < number.length; i++) {
            str += "零壹贰叁肆伍陆柒捌玖".charAt(number.charAt(i)) + unit.charAt(i);
        }
        ret = str
            .replace(/零(仟|佰|拾|角)/g, "零")
            .replace(/(零)+/g, "零")
            .replace(/零(万|亿|元)/g, "$1")
            .replace(/(亿)万|(拾)/g, "$1$2")
            .replace(/^元零?|零分/g, "")
            .replace(/元$/g, "元");
        if (ret.indexOf("分") < 0 && ret.indexOf("角") < 0) {
            ret = ret + "整"
        }
    }
    return ret;
};
//转二维数组(树结构)  list 数据源   pid 根节点（最外层节点）标识
export function arrayTree(list, pid) {
    var arr = []
    list.forEach(item => {
        if (item.pid === pid) {
            const children = this.arrayTree(list, item.id)
            if (children.length) {
                item.children = children
            }
            arr.push(item)
        }
    })
    return arr
}
// 随机颜色
export function randomColor() {
    return '#' + Math.random().toString(16).substring(2, 8).padEnd(6, '0')
  }
 
//千分位转换.加补零
export function thousands(val) {
    if (val) {
      let num = Number(val);
      let str = num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
      return str
    }
  }
// 格式化时间
export function ctime(time) {
    const date = new Date(time);
    const y = date.getFullYear();
    const m = (date.getMonth() + 1).toString().padStart(2, "0");
    const d = date.getDate().toString().padStart(2, "0");
    const h = date.getHours().toString().padStart(2, "0");
    const mm = date.getMinutes().toString().padStart(2, "0");
    const s = date.getSeconds().toString().padStart(2, "0");
    return `${y}-${m}-${d} ${h}:${mm}:${s}`
}
// 在下标后添加 字符    console.log(this.insertNum('你好', 1, '啊'))     //你啊好
export function insertNum(source, start, newStr) {
    return source.slice(0, start) + newStr + source.slice(start) //传下标

}
// 在匹配字符串后添加 字符     console.log(this.insertStr('你好3和', '3', '啊'))
export function insertStr(source, start, newStr) {
    return source.slice(0, source.indexOf(start) + 1) + newStr + source.slice(source.indexOf(start) + 1)//传匹配字符
}
// 随机数
export function randomId(len = 11) {
    if (len > 11) {
      len = 11
    }
    return Math.random().toString(36).substring(2, 2 + len).padEnd(len, '0')
  }

// 随机20位字母加数字生成规则 getRanNum(10)
export function getRanNum(number) {
    var result = [];
    for (var i = 0; i < 3; i++) {
        var ranNum = Math.ceil(Math.random() * 25);
        result.push(String.fromCharCode(65 + ranNum));
    }
    var rnd = "";
    for (var i = 0; i < number; i++)
        rnd += Math.floor(Math.random() * 10);
    return result.join('') + rnd;
}
//查询当前月最后一天  console.log(this.$getLastDay())
export function getLastDay() {
    var y = new Date().getFullYear(); //获取年份
    var m = new Date().getMonth() + 1; //获取月份
    var d = new Date(y, m, 0).getDate(); //获取当月最后一日
    m = m < 10 ? '0' + m : m; //月份补 0
    d = d < 10 ? '0' + d : d; //日数补 0
    return [y, m, d].join("-")
}
// 根据日期返回星期几  console.log(this.getWeekday("2023-01-23"));
export function getWeekday(date) {
    var weekArray = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
    var week = weekArray[new Date(date).getDay()];
    return week;
}
//返回N是否是质数  
export function isPrime(n) {
    for (var i = 2; i <= Math.sqrt(n); i++) {
        // console.log(i);
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}
//判断传进来的是什么数据类型   
export function dataType(data) {
    if (typeof (data) == 'object') {
        if (data) {
            if (data instanceof Array) {
                return 'array'
            } else if (data instanceof Date) {
                return 'date'
            } else {
                return 'object'
            }
        } else {
            return 'null'
        }
    } else {
        return typeof (data);
    }
}
//数组去重
export function unique1(arr) {
    return [...new Set(arr)]
}
//获得滚动条的滚动距离 @mousewheel='showOut'
export function getScrollOffset() {
    if (window.pageXOffset) {
        return {
            x: window.pageXOffset,
            y: window.pageYOffset
        }
    } else {
        return {
            x: document.body.scrollLeft + document.documentElement.scrollLeft,
            y: document.body.scrollTop + document.documentElement.scrollTop
        }
    }
}
//获得视口的尺寸
export function getViewportOffset() {
    if (window.innerWidth) {
        return {
            w: window.innerWidth,
            h: window.innerHeight
        }
    } else {
        // ie8及其以下
        if (document.compatMode === "BackCompat") {
            // 怪异模式
            return {
                w: document.body.clientWidth,
                h: document.body.clientHeight
            }
        } else {
            // 标准模式
            return {
                w: document.documentElement.clientWidth,
                h: document.documentElement.clientHeight
            }
        }
    }
}
//普通数组排序 var arr = [3,1,2,4,5,6,8,0,1]; console.log(arr.sort(this.compareTo));
export function compareTo(object1, object2) {
    if (object1 < object2) {
        return -1;
    } else if (object1 > object2) {
        return 1;
    } else {
        return 0;
    }
}
//对象数组中，根据某一属性对数组对象排序   console.log(arr.sort(this.createComparator("age")));
// var arr = [{ name: '王五', age: 23 }, { name: '李四', age: 29 }, { name: '张三', age: 25 }];
export function createComparator(property) {
    return function (object1, object2) {
        var value1 = object1[property];
        var value2 = object2[property];
        if (value1 < value2) {
            return -1;
        } else if (value1 > value2) {
            return 1;
        } else {
            return 0;
        }
    }
}
//下载pdf 文件
export function FileSaverPdf(url, name) {
    var oReq = new XMLHttpRequest();
    // The Endpoint of your server 
    var URLToPDF = url

    // Configure XMLHttpRequest
    oReq.open("GET", URLToPDF, true);

    // Important to use the blob response type
    oReq.responseType = "blob";

    // When the file request finishes
    // Is up to you, the configuration for error events etc.
    oReq.onload = function () {
        // Once the file is downloaded, open a new window with the PDF
        // Remember to allow the POP-UPS in your browser
        var file = new Blob([oReq.response], {
            type: 'application/pdf'
        });

        // Generate file download directly in the browser !
        saveAs(file, name + ".pdf");
    };
    oReq.send();
}
//点我复制 input
export function textCopy(text) {
    let oInput = document.createElement('input')
    oInput.value = text
    document.body.appendChild(oInput)
    oInput.select()
    document.execCommand("Copy")
    oInput.style.display = 'none'
    document.body.removeChild(oInput)
}
//去除字符串空格
export function trim(str) {
    return str.replace(/^[" "||"　"]*/, "").replace(/[" "|"　"]*$/, "");// 去除头和尾
    return str.replace(/\s/g, '');//去除所有空格
    return str.replace(/(\s*$)/g, "");//去除右边所有空格
}
//是否是邮箱
export function isEmail(emailStr) {
    var reg = /^[a-zA-Z0-9]+([._-]*[a-zA-Z0-9]*)*@[a-zA-Z0-9]+.[a-zA-Z0-9{2,5}$]/;
    var result = reg.test(emailStr);
    if (result) {
        return true
    } else {
        return false
    }
}
//是否是手机号
export function isPhone(phone) {
    var reg = /^1\d{10}$/;
    if (reg.test(phone)) {
        return true
    } else {
        return false
    }
}
